<?php
namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use App\Models\BackstageModel;
use App\Models\CommonModel;
use Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;

// require_once '../app/libary/captcha/Code.class.php';

class ArticleController extends BCommonController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/backstage/article/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('guest', ['except' => 'logout']);
    // }

    public function index(){
        if(isset($_GET['type_id']) && intval($_GET['type_id'])!=0){
            $type_id = intval($_GET['type_id']);
            if(isset($_GET['keywords'])){
                $keywords = trim($_GET['keywords']);
                $list = DB::table('article')->where('title','like','%'.$keywords.'%')->where('type_id',$type_id)->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }else{
                $list = DB::table('article')->where('type_id',$type_id)->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }
        }else{
            if(isset($_GET['keywords'])){
                $keywords = trim($_GET['keywords']);
                $list = DB::table('article')->where('title','like','%'.$keywords.'%')->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }else{
                $list = DB::table('article')->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }
        }
        // dump({{ $list->links() }});exit;
        $cate = BackstageModel::getCateList();
        foreach($list as $key=>$v){
            $typename = CommonModel::getOne('article_category',['id'=>$v->type_id]);
            // dump($typename->type_name);exit;
            $list[$key]->type_name = $typename->type_name;
        }
        return view('backstage/article/index',['cate'=>$cate,'list'=>$list]);
    }
    public function add(){
        $cate = BackstageModel::getCateList();
        return view('backstage/article/add',['cate'=>$cate]);
    }
    public function doadd(Request $request){
        // dd($request->all());
        if($request->isMethod('POST')){
            
            $data = $request->except('_token');
            $file = $request->file('art_img');
            // dd($data);exit;
            // 文件是否上傳成功
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('status' => 0,'message'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('status' => 0,'message'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                    $article['art_img'] = '/uploads/article/'.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('article')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }
                }
            }
            
            $article['type_id'] = intval($data['type_id']);
            $article['title'] = trim($data['title']);
            $article['art_content'] = trim($data['art_content']);

            if(empty($data['art_writer'])){
                $article['art_writer'] = session('admin')->user_name;
            }else{
                $article['art_writer'] = trim($data['art_writer']);
            }
            $article['art_keyword'] =trim($data['art_keyword']);
            $article['art_set'] = $data['art_set'];
            $article['art_url'] = $data['art_url'];

            if(empty($data['sort_order'])){
                $article['sort_order'] = 0;
            }else{
                $article['sort_order'] = intval($data['sort_order']);
            }
            $article['art_info'] = $data['art_info'];
            $article['is_hidden'] = $data['is_hidden'];
            $article['art_time'] = time();
            $newid = CommonModel::addDataGetId('article',$article);
            if($newid){
                $arrJson = array('status' => 1, 'message'=>'文章添加成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'文章添加失敗');
            }
            return json_encode($arrJson);
        }
    }
    public function edit($id){
        $table = 'article';
        $data =['id'=>$id];
        $art = CommonModel::getOne($table,$data);
        // dd($art);
        $cate = BackstageModel::getCateList();
        return view('backstage/article/edit',['cate'=>$cate,'art'=>$art]);
    }
    public function doedit(Request $request){
        // dd($request->all());
        if($request->isMethod('POST')){
            $data = $request->except('_token');
            $file = $request->file('art_img');
            if(empty($data['id'])){
                return json_encode(['status' => 0, 'message'=>'未能獲取文章ID']);
            }
            $id = intval($data['id']);
            // dd($data);exit;
            // 文件是否上傳成功
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('status' => 0,'message'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('status' => 0,'message'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                    $article['art_img'] = '/uploads/article/'.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('article')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }
                }
            }
            
            $article['type_id'] = intval($data['type_id']);
            $article['title'] = trim($data['title']);
            $article['art_content'] = trim($data['art_content']);

            if(empty($data['art_writer'])){
                $article['art_writer'] = session('admin')->user_name;
            }else{
                $article['art_writer'] = trim($data['art_writer']);
            }
            $article['art_keyword'] =trim($data['art_keyword']);
            $article['art_set'] = $data['art_set'];
            $article['art_url'] = $data['art_url'];
            if(empty($data['sort_order'])){
                $article['sort_order'] = 0;
            }else{
                $article['sort_order'] = intval($data['sort_order']);
            }
            $article['art_info'] = $data['art_info'];
            $article['is_hidden'] = $data['is_hidden'];
            $save = CommonModel::updateData('article',['id'=>$id],$article);
            if($save == true){
                CommonModel::updateData('article',['id'=>$id],['art_time'=>time() ]);
                $arrJson = array('status' => 1, 'message'=>'文章修改成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'文章修改失敗');
            }
            return json_encode($arrJson);
        }
    }

    public function show($id){
        $table = 'article';
        $data =['id'=>$id];
        $art = CommonModel::getOne($table,$data);
        // dd($art);
        return view('backstage/common/article',['art'=>$art]);
    }
    


}
